"""Header_Information
------------------------------------
    File_Name: auth
    Author: RR9
    Date: 2024/10/16
    Description: 认证示例
------------------------------------
"""
from datetime import datetime, timedelta, timezone

import jwt
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

# jwt
from passlib.context import CryptContext
from jwt.exceptions import InvalidTokenError

from fastapi import APIRouter
from pydantic import BaseModel
from starlette import status

router = APIRouter()

SECRET_KEY = "1234567890"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 1

fake_users_db = {
    "johndoe": {
        "username": "johndoe",
        "full_name": "John Doe",
        "email": "johndoe@example.com",
        "hashed_password": "$2b$12$1VQ3jagHWIIMcuBx4pzYJeugI3fcR3JRUo7qNh.Swr9uJIsMb5ST6",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Wonderson",
        "email": "alice@example.com",
        "hashed_password": "$2b$12$6BA3JHYuXW98TbyK/EBDD.6gkTAK6w/gRGxcHFs3HlLUzNOV.UE0i",
        "disabled": True,
    },
    "yang": {
        "username": "yang",
        "full_name": "yangzhide",
        "email": "yanghzide@example.com",
        "hashed_password": "$2b$12$wjLbfGY8TlZsqAkjmExs9OnIDaEJ7rp/xH6UsovjzxfbBILs13Xze",
        "disabled": False,
    },
}
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/v1/token")


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    desabled: bool | None = None


class UserInDB(User):
    hashed_password: str


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """ 验证密码 """
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    """ 密码哈希 """
    return pwd_context.hash(password)


def authenticate_user(fake_db, username: str, password: str):
    """ 验证用户 """
    user = get_user(fake_db, username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user


def create_access_token(data: dict, expires_delta: timedelta | None = None):
    """ 创建token
    默认效期 3分钟
    """
    to_encode = data.copy()
    if expires_delta:
        expires = datetime.now(timezone.utc) + expires_delta
    else:
        expires = datetime.now(timezone.utc) + timedelta(minutes=1)

    to_encode.update({"exp": expires})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)


def fake_decode_token(token: str):
    """ 返回UserInDB模型，包含密码属性 """
    user = get_user(fake_users_db, token)
    return user


async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"}
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except InvalidTokenError:
        raise credentials_exception
    user = get_user(fake_users_db, token_data.username)
    if user is None:
        raise credentials_exception
    return user


async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if current_user.desabled:
        raise HTTPException(status_code=400, detail="用户状态不可用")
    return current_user


@router.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的用户名或密码",
            headers={'WWW-Authenticate': 'Bearer'}
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@router.post("/users/me", summary="当前用户")
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    return current_user


@router.post("users/me/items")
async def read_own_items(current_user: User = get_current_active_user):
    return [{"item_id": "Foo", "owner": current_user.username}]
